package com.taotao.service;

import com.taotao.common.pojo.PictureResult;
import com.taotao.common.utils.ExceptionUtil;
import com.taotao.common.utils.FtpUtil;
import com.taotao.common.utils.IDUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;


/**
 * PictureServiceImpl
 * Created by heqianqian on 2017/7/6.
 */
@Service
public class PictureServiceImpl implements PictureService {

    @Value("${FTP_BASE_PATH}")
    private String FTP_BASE_PATH;
    @Value("${IMAGE_BASE_URL}")
    private String IMAGE_BASE_URL;
    @Value("${FTP_ADDRESS}")
    private String FTP_ADDRESS;
    @Value("${FTP_PORT}")
    private Integer FTP_PORT;
    @Value("${FTP_USERNAME}")
    private String FTP_USERNAME;
    @Value("${FTP_PASSWORD}")
    private String FTP_PASSWORD;

    @Override
    public PictureResult uploadFile(MultipartFile uploadFile) {
        //判断图片是否为空
        if (null == uploadFile || uploadFile.isEmpty()) {
            return PictureResult.error("上传图片为空");
        }
        //取文件扩展名
        String originalFilename = uploadFile.getOriginalFilename();
        String ext = originalFilename.substring(originalFilename.lastIndexOf("."));
        //生成新文件名
        //可以使用UUID生成
        //UUID.randomUUID();
        //可以是时间+随机数字生成文件名
        String imageName = IDUtils.genImageName();
        //把图片上传到服务器
        DateTime dateTime = new DateTime();
        String filePath = dateTime.toString("/yyyy/MM/dd");
        try {
            FtpUtil.uploadFile(FTP_ADDRESS, FTP_PORT, FTP_USERNAME, FTP_PASSWORD,
                    FTP_BASE_PATH, filePath, imageName + ext, uploadFile.getInputStream());
        } catch (Exception e) {
            e.printStackTrace();
            return PictureResult.error(ExceptionUtil.getStackTrace(e));
        }
        //返回结果 生成一个可访问到的地址
        return PictureResult.ok(IMAGE_BASE_URL + filePath + "/" + imageName + ext);
    }
}
